package com.ruoyi.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.system.mapper.RnxCountMapper;
import com.ruoyi.system.service.IRnxCountService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @ClassName RnxCountServiceImpl
 * @Description 统计服务
 * @Author yangtao2
 * @Date 2022/8/5 15:30
 * @Version 1.0
 **/
@Slf4j
@Service
public class RnxCountServiceImpl implements IRnxCountService {

	private static DateTimeFormatter md = DateTimeFormatter.ofPattern("MM-dd");

	@Resource
	RnxCountMapper mapper;

	@Override
	public Map headCount() {
		Map m = new HashMap(8);
		//获取最近30天的时间
		List<String> dates = new LinkedList<>();
		LocalDate localDate = LocalDate.now();
		for (int i = 60; i > 0; i--) {
			dates.add(localDate.minusDays(i).format(md));
		}
		//填充日期
		m.put("date",dates);
		//处理员工录入数据
		List<Map> inviteLogCount = mapper.getInviteLogCount();
		Map<String,Long> dataInvite = transferList(inviteLogCount,"t","c");
		//处理短信下发数据
		List<Map> smsSendLogCount = mapper.getSmsSendLogCount();
		Map<String,Long> dataSms = transferList(smsSendLogCount,"t","c");
		//数据容器准备
		List<Long> inviteList = new LinkedList<>();
		List<Long> smsList = new LinkedList<>();
		//填充0
		dates.forEach(
				d -> {
					// 这里填充一下年份
					String k = localDate.getYear() + "-" + d;
					inviteList.add(MapUtils.getLongValue(dataInvite,k,0L));
					smsList.add(MapUtils.getLongValue(dataSms,k,0L));
				}
		);
		//数据装填
		m.put("data_i",inviteList);
		m.put("data_s",smsList);
		log.info("数据获取完成:{}", JSONObject.toJSONString(m));
		return m;
	}

	/**
	 * 将list数据转为map
	 * @param list
	 * @param k
	 * @param v
	 * @return
	 */
	private Map<String,Long> transferList(List<Map> list,String k,String v){
		Map<String,Long> map = new HashMap();
		if(list == null || list.size() == 0)return map;
		list.forEach(
				e -> {
					map.put(e.get(k).toString(), Convert.toLong(e.getOrDefault(v,0L)));
				}
		);
		return map;
	}


}
